<?php

/* @project : Template
 * @auther  : 青云
 * @date    : 2018/1/10
 * @desc    : 菜单模型
 */

namespace app\common\model;

use think\Model;

class Menu extends Model
{

	function getAccessList($user_id = null)
	{
		if (empty($user_id)) {
			$user_id = get_user_id();
		}

		$menu = db('menu');
		$menu->alias('menu');
		$menu->field("menu.icon,menu.badge,menu.sort*1 sort, menu.id, menu.pid, menu.name, menu.url,sum(role_menu.admin) as 'admin',sum(role_menu.write) as 'write',sum(role_menu.read) as 'read'");
		$menu->join('role_menu', 'menu.id=role_menu.menu_id');
		$menu->join('role_admin', 'role_admin.role_id=role_menu.role_id');

		$where[] = array('role_admin.admin_id', 'eq', $user_id);
		$where[] = array('menu.is_del', 'eq', 0);

		$access_list = $menu->where($where)->group('menu.id')->order('sort asc')->select();


		return $access_list;
	}

	// 获取当前模块名称
	public function getModuleNameAttr($value, $data)
	{
		$module_arr = config('module_arr');

		if (isset($module_arr[$data['module']])) {
			$module_name = $module_arr[$data['module']];
		} else {
			$module_name = '';
		}
		return $module_name;
	}

	function getMenuList()
	{
		$where_menu[] = array('is_del', 'eq', 0);

		$list = $this->where($where_menu)->order('sort asc')->select()->toArray();

		return $list;
	}

	function getAuth($url, $user_id = null)
	{
		if (empty($user_id)) {
			$user_id = get_user_id();
		}

		$menu = db('menu');
		$menu->alias('menu');
		$menu->field("sum(role_menu.admin) as 'admin',sum(role_menu.write) as 'write',sum(role_menu.read) as 'read'");
		$menu->join('role_menu', 'menu.id=role_menu.menu_id');
		$menu->join('role_user', 'role_user.role_id=role_menu.role_id');
		$where[] = array('role_user.user_id', 'eq', $user_id);
		$where[] = array('menu.is_del', 'eq', 0);
		$where[] = array('menu.url', 'eq', $url);

		$menu->where($where);
		$menu->group('menu.id');
		$menu->order('menu.sort asc');

		return $menu->find();
	}

	function hasChild($id)
	{
		$where[] = ['pid', 'eq', $id];

		return $this->where($where)->count();
	}

	function getDataAttr($value, $data)
	{
		$where   = array();
		$where[] = ['pid', 'eq', $data['id']];
		$where[] = ['is_del', 'eq', 0];
		$data    = model('Menu')->where($where)->select()->toArray();
		return $data;
	}

}
